#include "Engine.h"

Engine *Engine::pInstance = NULL;

Engine *Engine::getInstance(){
	if(pInstance == NULL){
		pInstance = new Engine();	
	}

	return pInstance;
}

Engine::Engine(){
	SDL_Init(SDL_INIT_EVERYTHING);

	currentState = NULL;

	running = true;

	state = STATE_PLAYING;
}

void Engine::mainLoop(){
	while(running){
		startTimer();

		manageState();

		if(currentState->i.setQuit)
			running = false;

		currentState->Update();
		currentState->Render();
	}

	if(getTicks() < (1000 / 60))
		SDL_Delay((1000 / 60) - getTicks());  //Don't let the game run too fast!
}

void Engine::changeState(int newState){
	if(newState != STATE_NULL){
		this->state = newState;
	}
}

void Engine::manageState(){
	if(state != STATE_NULL)
		delete currentState;

	switch(state){
		case STATE_PLAYING:
			currentState = new World();

			break;
		case STATE_MENU:
			//currentState = new Menu();
			break;
		default:
			break;
	}

	state = STATE_NULL;
}

void Engine::startTimer(){
	ticks = SDL_GetTicks();
}

int Engine::getTicks(){
	return SDL_GetTicks() - ticks;
}


Engine::~Engine(){
	SDL_Quit();

	delete currentState;
}